package logic

import (
	"context"
	"xialou_platform/app/constx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/services/system/rpc/systemClient"
	"xialou_platform/services/wallet/rpc/walletClient"

	"xialou_platform/services/wallet/api/internal/svc"
	"xialou_platform/services/wallet/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type WithdrawalPaymentLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWithdrawalPaymentLogic(ctx context.Context, svcCtx *svc.ServiceContext) WithdrawalPaymentLogic {
	return WithdrawalPaymentLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WithdrawalPaymentLogic) WithdrawalPayment(req *types.WithdrawalPaymentReq) error {
	uid, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return err
	}

	joinPayUserNo, err := l.svcCtx.SystemRpc.SysConfigByKey(l.ctx, &systemClient.KeyReq{Key: constx.JoinPayUserNo})
	if err != nil {
		return err
	}
	joinPayMerchantKey, err := l.svcCtx.SystemRpc.SysConfigByKey(l.ctx, &systemClient.KeyReq{Key: constx.JoinPayMerchantKey})
	if err != nil {
		return err
	}
	joinPayCallbackUrl, err := l.svcCtx.SystemRpc.SysConfigByKey(l.ctx, &systemClient.KeyReq{Key: constx.JoinPayCallbackUrl})
	if err != nil {
		return err
	}
	_, err = l.svcCtx.WalletRpc.WithdrawalPayment(l.ctx, &walletClient.WithdrawalPaymentReq{
		Id:                 respx.IDParse(req.Id).GetInt64(),
		UpdateBy:           uid,
		JoinPayUserNo:      joinPayUserNo.ConfigValue,
		JoinPayMerchantKey: joinPayMerchantKey.ConfigValue,
		JoinPayCallbackUrl: joinPayCallbackUrl.ConfigValue,
	})
	if err != nil {
		return err
	}
	return nil
}
